// 对象克隆
export const DeepCopy = function (obj) {
  let str
  let newobj = obj.constructor === Array ? [] : {}
  if (typeof obj !== 'object') {
    return
  } else if (window.JSON) {
    str = JSON.stringify(obj)
    newobj = JSON.parse(str)
  } else {
    for (var i in obj) {
      newobj[i] = typeof obj[i] === 'object' ? DeepCopy(obj[i]) : obj[i]
    }
  }
  return newobj
}
// 获取值类型
// 支持校验的值类型
// null undefined Number Array String Boolean 等等
export function getValueType (val) {
  if (val === null) {
    return 'null'
  }
  if (typeof val === 'undefined') {
    return 'undefined'
  }
  let typeStr = Object.prototype.toString.call(val)
  let reg = /\[object\s(\S*)]$/g
  let type = typeStr.replace(reg, (val, $1) => $1)
  return type
}

export function valueTypeTransform (val, toValueType) {
  // 可支持转换的值类型
  let typeArr = [String, Number, Boolean, Array]
  if (typeArr.indexOf(toValueType) === -1) {
    throw new Error('所需转换值的类型未知')
  }
  if (val instanceof toValueType) {
    return val
  }
  if (toValueType === Array) {
    return [val]
  } else {
    return toValueType(val)
  }
}

export function valueTypeTransformAll (params, formRule) {
  let paramsTarget = {}
  let copy = formRule
  if (params) {
    for (let key in params) {
      let ruleItem = copy.find((item, index) => {
        return item.id.indexOf(key) > -1
      })
      // console.log(ruleItem)
      if (ruleItem && ruleItem['type']) {
        paramsTarget[key] = valueTypeTransform(params[key], ruleItem['type'])
      }
    }
    // console.log(params)
    // console.log(formRule)
    // console.log(paramsTarget)
    return paramsTarget
  }
}
